import schedule
import time
import subprocess
import logging
import signal
import sys

# 配置日志记录
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)


def run_ossd_script():
    try:
        logging.info("正在执行 ossd.py...")
        result = subprocess.run(["python", "ossd.py"], check=True)
        logging.info(f"ossd.py 执行完成，返回码: {result.returncode}")
    except subprocess.CalledProcessError as e:
        logging.error(f"执行 ossd.py 时出错，返回码: {e.returncode}")
    except Exception as e:
        logging.exception(f"发生异常: {e}")


def exit_gracefully(signum, frame):
    logging.info("收到终止信号，准备退出...")
    sys.exit(0)


if __name__ == "__main__":
    # 注册终止信号处理（Ctrl+C 或 kill）
    signal.signal(signal.SIGINT, exit_gracefully)
    signal.signal(signal.SIGTERM, exit_gracefully)

    logging.info("定时任务已启动，每 5 分钟执行一次 ossd.py")

    # 每 5 分钟执行一次
    schedule.every(5).minutes.do(run_ossd_script)

    try:
        while True:
            schedule.run_pending()
            time.sleep(1)
    except KeyboardInterrupt:
        exit_gracefully(None, None)